<template>
  <div>
    <el-card>
      <el-form ref="editPwdForm" label-width="80px" :model="editPwdForm"
               style="width:30%" :rules="rules"
      >
        <el-form-item label="账号" prop="username">
          <el-input v-model="editPwdForm.username" :disabled="true" />
        </el-form-item>
        <el-form-item label="旧密码" prop="oldPwd">
          <el-input v-model="editPwdForm.oldPwd" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd">
          <el-input v-model="editPwdForm.newPwd" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('editPwdForm')">
            重置密码
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { editPwd } from '@/api/activity'
const { createHmac } = require('crypto')
export default {
  data() {
    let validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入账户'))
      } else {
        callback()
      }
    }
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入旧密码'))
      } else {
        callback()
      }
    }
    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'))
      } else if (value === this.editPwdForm.oldPwd) {
        callback(new Error('两次输入密码需不一致!'))
      } else {
        callback()
      }
    }
    return {
      editPwdForm: {
        username: '',
        oldPwd: '',
        newPwd: ''
      },
      rules: {
        username: [
          {required: true, validator: validateName, trigger: 'blur' }
        ],
        oldPwd: [
          {required: true, validator: validatePass, trigger: 'blur' }
        ],
        newPwd: [
          {required: true, validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.editPwdForm.username = localStorage.getItem('username')
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('submit!', this.editPwdForm)
          const hash = createHmac('sha256', 'cmsSecret')
            .update(this.editPwdForm.newPwd)
            .digest('hex')
          editPwd({...this.editPwdForm, newPwd: hash}).then(res => {
            console.log('----', res)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style>

</style>
